package com.jfinalxueyuan.eclipse.caseconversion;

import java.lang.reflect.Method;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.AbstractTextEditor;


/**
 * 处理快捷键的具体handler
 * @author 小木-JFinal学院 jfinalxueyuan.com
 * @email 909854136@qq.com
 * @date 2018年11月8日 下午9:11:39
 */
public class CaseConversionHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		if (page!=null) {
			ISelection selection=page.getSelection();
			if(selection != null&&selection.isEmpty()==false) {
				if(selection instanceof TextSelection) {
					TextSelection textSelection=(TextSelection)selection;
					String text=textSelection.getText().trim();
					if(StrUtil.isNotBlank(text)) {
						boolean isLow=Character.isLowerCase(text.charAt(0));
						if(isLow) {
							text=StrUtil.upperFirst(text);
						}else {
							text=StrUtil.lowerFirst(text);
						}
						AbstractTextEditor textEditor = (AbstractTextEditor) page.getActiveEditor().getAdapter(AbstractTextEditor.class);
						try {
							Method me = AbstractTextEditor.class.getDeclaredMethod("getSourceViewer");
							me.setAccessible(true);
							Object viewer = me.invoke(textEditor);
							if (viewer != null) {
								ISourceViewer sourceViewer = (ISourceViewer) viewer;
								IDocument document=sourceViewer.getDocument();
								document.replace(textSelection.getOffset(), textSelection.getLength(), text);
								sourceViewer.setSelectedRange(textSelection.getOffset(), textSelection.getLength());
								
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				
			}
		}
		return null;
	}
}
